package com.demo.test.tcp;

import org.junit.Test;

import java.math.BigDecimal;
import java.math.BigInteger;

public class HexToDecimalConverter {

    @Test
    public void m1(){
        long startTime = System.currentTimeMillis();

        System.out.println(parseHex4("ffce"));
        System.out.println(parseHex4("01cb"));
        System.out.println(parseHex8("46ccc4fa"));

        System.out.println(parseHex4Str("ffce"));
        System.out.println(parseHex4Str("01cb"));
        System.out.println(parseHex8Str("46ccc4fa"));

        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }

    /**
     * 十六进制转负数

     * (2个字节的)
     */
    public static double parseHex4(String num) {
        if (num.length() != 4) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        int ret = Integer.parseInt(num, 16);
        ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
        return ret;
    }

    /**
     * 十六进制转负数

     * (4个字节的)
     */
    public static double parseHex8(String num) {
        if (num.length() != 8) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        BigInteger in = new BigInteger(num,16);
        return in.doubleValue();
    }


    /**
     * 十六进制转负数

     * (2个字节的)
     */
    public static String parseHex4Str(String num) {
        if (num.length() != 4) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        int ret = Integer.parseInt(num, 16);
        ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
        BigDecimal bigDecimal = new BigDecimal(ret);
        return bigDecimal.toString();
    }

    /**
     * 十六进制转负数

     * (4个字节的)
     */
    public static String parseHex8Str(String num) {
        if (num.length() != 8) {
            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
        }
        BigInteger in = new BigInteger(num,16);

        BigDecimal a = new BigDecimal(in);
        BigDecimal b = BigDecimal.valueOf(Math.pow(10, -7));
        String result = a.multiply(b).toString();
        return result;
    }


}